<template>
  <div class="search-container">
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon
        name="arrow-left"
        color="white"
        size="0.48rem"
        class="goback"
        @click="$router.back()"/>
      <!-- 搜索组件 -->
      <van-search
        v-focus
       @input="inputFn"
        v-model="keyword"
        placeholder="请输入搜索关键词"
        background="#007BFF"
        shape="round"
         @search="goto(keyword)"

        />
    </div >
    <!-- 搜索建议列表 -->
<ul class="sugg-list"    v-if="suggestList.length"      >
  <li class="sugg-item" v-for="(item , index) in suggestList "
   :key="index"
   v-html="highlight(item)"
   @click="goto(item)"
     >

  </li>

</ul>

<!-- 搜索历史 -->
<div class="search-history"   v-else >
  <!-- 标题 -->
  <van-cell title="搜索历史">
    <!-- 使用 right-icon 插槽来自定义右侧图标 -->
       <template #right-icon>
     <van-icon name="delete" class="search-icon" @click="clearHistoryFn"/>
       </template>
   </van-cell>

  <!-- 历史列表 -->
  <div class="history-list" >
    <span class="history-item"   v-for="(itme , index) in history"
     :key="index"
      @click="goto(itme)"
      >{{itme}}</span>
</div>
     <!-- 历史文字 -->
  </div>

  </div>
</template>

<script>

import { HISTORY_KEY } from '@/config'
import { setStorage, getStorage, removeStorage } from '@/utils/storage'
import { getSuggListAPI } from '@/api/search'
let timer

export default {
  name: 'search',
  data () {
    return {
      keyword: '', // 搜索关键字
      suggestList: [], // 建议关键字列表
      history: getStorage(HISTORY_KEY) || []
      // JSON.parse(localStorage.getItem('history')) || ['API', 'java', 'css', '前端', '后台接口', 'python'] // 搜索历史
    }
  },
  methods: {
    //   输入框 防抖 input 事件触发
    inputFn () {
      clearTimeout(timer)
      timer = setTimeout(async () => {
        if (!this.keyword) {
          this.suggestList = []
          return
        }

        // 联想建议列表
        const res = await getSuggListAPI({
          keyword: this.keyword
        })
        this.suggestList = res.data.options
      }, 500)
    },
    // 匹配变红
    highlight (str) {
      const regexp = new RegExp(this.keyword, 'ig')
      return str.replace(regexp, (match) =>
       `<span style="color: red">${match}</span>`
      )
    },
    // 三处跳转
    goto (keywords) {
      // 数据持久化
      if (!this.history.includes(keywords)) {
        this.history.push(keywords)
      }
      setStorage(HISTORY_KEY, this.history)
      // localStorage.setItem('history', JSON.stringify(this.history))
      this.$router.push(`/search/${keywords}`)
    },
    // 清空历史记录
    async clearHistoryFn () {
      try {
        await this.$dialog.confirm({
          title: '清空历史记录',
          message: ' 清空内容'
        })
        // 清空vue数据
        this.history = []
        // 清空本地
        removeStorage(HISTORY_KEY)
        this.$notify({ type: 'success', message: '清空' })
      } catch (e) {
        this.$notify({ type: 'primary', message: '以取消' })
      }
    }

  }
}
</script>

<style scoped lang="less">
.search-header {
  display: flex;
  align-items: center;
  height: 46px;
  background-color: #007bff;
  overflow: hidden;
  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }
  /*搜索组件*/
  .van-search {
    flex: 1;
  }
}
/*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

/**搜索历史 */
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
